"""
@author: xxw
@file: user.py.py
@time: 2023/8/1 19:31
"""
from werkzeug.security import generate_password_hash

from . import db
import datetime


#API授权表的模型
#多对多的关系
app_permission = db.Table("app_permission",
                          db.Column("api_id", db.ForeignKey("api_token.id")),
                          db.Column("permission_id", db.ForeignKey("api_permission.id"))
                          )

# api_token表
#存放的是授权密钥，以及授权id
class ApiToken(db.Model):
    __tablename__ = "api_token"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    appid = db.Column(db.String(128), nullable=False)
    secretkey = db.Column(db.String(128), nullable=False)
    #通过中间表去创建多对多的关系
    manage = db.relationship("ApiPermission", secondary=app_permission, backref="token")

#存放的是授权的url
class ApiPermission(db.Model):
    __tablename__ = "api_permission"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    url = db.Column(db.String(128), nullable=False)
    method_type = db.Column(db.String(128), nullable=False)


# 用户信息表
class UserInfo(db.Model):
    __tablename__ = "Users"
    user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50))
    _password = db.Column(db.String(200))
    regist_time = db.Column(db.Date, default=datetime.date.today)

    @property  # 自动根据函数名生成两个装饰器 --》password.setter  password.delete
    def password(self):
        return self._password
    # user.password()  --> print(user.password)

    # 定义属性之前做一些检测、转换
    # user.password = xxx
    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    @classmethod  # 类方法 第一个参数代表类本身
    def create_user(cls, username, password):
        user = cls()  # 创建实例现象
        user.username = username
        user.password = password  # 调用password.setter 装饰函数，强制性要求存hash值
        db.session.add(user)
        db.session.commit()